<?php // -*- C++ -*-
 
 // $Id: langchooser.php,v 1.3 2006/04/29 12:20:06 patrick Exp $
 
 /*
 
  This script tries to guess what language to use for
  language dependent operations (lookup, search, books
  page display, etc.), considering all possible factors
  affecting language selection.
 
  After this script run, $LANG is set to the preferred
  language, or is the empty string, if no manual is
  available on the current mirror site.
   
  $EXPL_LANG will also be set to the explicitly provided
  language, or will not exist if there are only implications
  on the preferred language.
  
  $UA_LANGS will contain the user agent language settings
  parsed as an array. The language names are corrected for
  php.net usage in this array. This is just to present to
  the user in case he would like to get information on the
  parsed language information (see /my.php).
 
  The $_SERVER['STRIPPED_URI'] var is also set to the
  stripped request URI (in case of a shortcut, the
  language is stipped, so the shortcut handling code
  is not bothered with it).
 
 */
 

function parse_accept_language()
{ 
    // Specified by the user via the browser's Accept Language setting
    // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
    $browser_langs = array(); $parsed_langs = array();
 
    // Check if we have $_SERVER['HTTP_ACCEPT_LANGUAGE'] set
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $browser_accept = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
	$one = 1.0;
        // Go through all language preference specs
        for ($i = 0; $i < count($browser_accept); $i++) {
            // The language part is either a code or a code with a quality
            // We cannot do anything with a * code, so it is skipped
           // If the quality is missing, it is assumed to be 1 according to the RFC
	  // To account for the fact that browsers send stuff in priority order,
	  // decrement the value of "1" by .01 for each round....
	  // This will make "hu; en" sort "correctly".
            if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($browser_accept[$i]), $found)) {
                $quality = (isset($found[3]) ? (float) $found[3] : $one);
                $browser_langs[] = array($found[1], $quality);
		$one -= 0.01;
            }
            unset($found);
        }
    }
     // Order the codes by quality
    usort($browser_langs, "language_accept_order");
    return $browser_langs;
}

function best_language_from_accept_language()
{
  $preferences = parse_accept_language();
  $languages = languages_supported();
  # Formal algorithm: Match preferences one by one, picking the
  # first one that matches according to prefix match rule (RFC 2616 sec 14.4)
  foreach ($preferences as $langa) {
    $lang = $langa[0];
    $langsfound = array_values(preg_grep("/^$lang(-|$)/i", $languages));
    if ($langsfound) {
      return $langsfound[0];
    }
  }
  return "";
}
    
      
    
  

function code_not_yet_moved() {
 
    // For all languages found in the accept-language
    foreach ($browser_langs as $langdata) {
    
        // Translation table for accept-language codes and phpdoc codes
        switch($langdata[0]) {
            case "pt-br" : $langdata[0] = 'pt_br'; break;
            case "zh-cn" : $langdata[0] = 'zh'; break;
            case "zh-hk" : $langdata[0] = 'hk'; break;
            case "zh-tw" : $langdata[0] = 'tw'; break;
        }
        
        // We do not support flavors of languages (except the ones above)
        // This is not in conformance to the RFC, but it here for user
        // convinience reasons
        if (preg_match("!^(.+)-!", $langdata[0], $match)) {
            $langdata[0] = $match[1];
        }
        
        // Add language to priority order
        $parsed_langs[] = language_add($langdata[0], $languages);
    }
 
    // Language preferred by this mirror site
    language_add(default_language(), $languages);
 
    // Last default language is English
    language_add("en", $languages);
 
    // Try to find out what language is available on this mirror.
    // As most of the language dependant operations involve manual
    // page display (lookup, search, shortcuts), we will check for
    // the index file of manuals.
 /*
    foreach ($languages as $language) {
        if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/manual/$language/index.php")) {
            $selected = $language;
            break;
        }
    }
 */
    $selected = $languages[0];
    
    // Return with all found data
    return array($selected, $explicitly_specified, $parsed_langs);
 }
 
 
 // Add a language to the possible languages' list
 function language_add($langcode, &$langs)
 {
    global $LANGUAGES, $INACTIVE_ONLINE_LANGUAGES;
 
    // Make language code lowercase
    $langcode = strtolower($langcode);
 
    // The Brazilian Portuguese code needs special attention
    if ($langcode == 'pt_br') { $langcode = 'pt_BR'; }
 
    // Append language code in priority order if it is not
    // there already and supported by the PHP site. Try to
    // lower number of file_exists() calls to the minumum...
    if (!in_array($langcode, $langs) && isset($LANGUAGES[$langcode])
        && !isset($INACTIVE_ONLINE_LANGUAGES[$langcode])) {
        $langs[] = $langcode;
    }
    
    // Return with language code
    return $langcode;
 }
 
 // Order the array of compiled
 // accept-language codes by quality value
 function language_accept_order($a, $b)
 {
    if ($a[1] == $b[1]) { return 0; }
    return ($a[1] > $b[1]) ? -1 : 1;
 }
 
function display_chooser()
{
  global $self_url;

  // $array=parse_url($self_url);
  // print_r($array);
  
  // $self_url=$array[scheme] . "://" . $array[host] . $array[path];

  print
    "<form method=\"POST\" action=\"$self_url\">\n";

  print "<select name=\"language\">";
 
  foreach (languages_supported() as $lang) {
    print "<option value=\"" . language_locale($lang) . "\">"
      . language_name($lang);
    if ($lang == "en" && language_name($lang) != "English") {
      print " (English)";
    }
    print "</option>\n";
  }
  print "</select>\n";
  print "<input type=\"submit\" value=\"" . _("Change") . " (Change)\">" .
  "</form>";

}
